<?php

use utils\oss;
use utils\redis;
use utils\wechat_pay;

require_once __DIR__ . "/data.php";
require_once dirname(__DIR__) . "/dn_exception/get_exception.php";
deal_exception();
//http、http请求通信函数
function http($url, $type, $method, $body)
{
    $header = [];
    if ($type == "json") {
        array_push($header, "content-type:application/json");
    } else {
        array_push($header, "content-type:application/x-www-form-urlencoded");
    }
    $body = json_encode($body);
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    curl_setopt($curl, CURLOPT_FAILONERROR, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, true);
    if (!empty($body)) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
    }

    if (1 == strpos("$" . $url, "https://")) {
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    }
    $response=curl_exec($curl);

    // 解析响应头
    $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
    $headers = substr($response, 0, $header_size);
    $body = substr($response, $header_size);
    curl_close($curl);
    if (preg_match('/Content-Type: ([^;]+)/', $headers, $matches)) {
        $contentType = trim($matches[1]);
        if ($contentType === 'application/json') {//json响应体返回
            return json_decode($body, true);
        } else {//二进制或其他类型响应返回
            return  $body;
        }
    } else {
        return out_error('第三方接口返回未知类型数据！');
    }
}

function http_wechat($base_url,  $body)
{
    $redis = redis::con();
    $token=$redis->get('wechat_token');
    if(!$token){
        $token=(new wechat_pay())->getToken();
    }
    $redis->close();
    $url=$base_url."?access_token=$token";
    $res=http($url, 'json', 'POST', $body);
    if(isset($res['errcode'])&&$res['errcode']===40001){
        $token=(new wechat_pay())->getToken();
        $url=$base_url."?access_token=$token";
        $res=http($url, 'json', 'POST', $body);
    }
    return $res;
}

function http0($url, $type, $method, $body)
{
    $header = [];
    if ($type == "json") {
        array_push($header, "content-type:application/json");
    } else {
        array_push($header, "content-type:application/x-www-form-urlencoded");
    }
    $body = json_encode($body);
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    curl_setopt($curl, CURLOPT_FAILONERROR, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, false);
    if (!empty($body)) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
    }

    if (1 == strpos("$" . $url, "https://")) {
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    }
    return curl_exec($curl);
}

//统一正确结果输出函数
function out_right($data='')
{
    $res["code"] = 200;
    $res["msg"] = "success";
    $res["data"] = $data;
    return json_encode($res);
}
//统一带页码正确输出


//统一错误结果输出函数
function out_error($msg='未知错误！')
{
    $res["code"] = 400;
    $res["msg"] = $msg;
    $res["data"] = $msg;
    return json_encode($res);
}
function out_error_token()
{
    $res["code"] = 300;
    $res["msg"] = "token无效或过期！";
    $res["data"] = "token无效或过期！";
    return json_encode($res);
}

function out_not_login()
{
    $res["code"] = 800;
    $res["msg"] = "未注册！";
    $res["data"] = "未注册！";
    return json_encode($res);
}

//链接数据库
function con()
{

    $con = mysqli_connect($GLOBALS["mysql_address"], $GLOBALS["mysql_account"], $GLOBALS["mysql_password"], $GLOBALS["mysql_database"]);
    mysqli_query($con, "set names 'utf8'");

    return $con;
}

function http_pay($url, $sign, $method, $body)
{
    $header = array(
        $sign,
        'Accept: application/json',
        'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
    );

    array_push($header, "content-type:application/json");

    $body = json_encode($body);
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    curl_setopt($curl, CURLOPT_FAILONERROR, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, false);
    if (!empty($body)) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
    }

    if (1 == strpos("$" . $url, "https://")) {
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    }
    return json_decode(curl_exec($curl), true);
}

//处理接口响应
function response($content){
    //RSA加密算法
    //openssl_private_encrypt($content, $encrypted, $GLOBALS['private_key']);
    //AES加密算法
    return urlencode(base64_encode(openssl_encrypt($content, 'AES-256-CBC', $GLOBALS['aes_key'], OPENSSL_RAW_DATA, $GLOBALS['aes_iv'])));
   // return base64_encode(openssl_encrypt($content, 'AES-256-CBC', $GLOBALS['aes_key'], OPENSSL_RAW_DATA, $GLOBALS['aes_iv']));
}

//获取无限制的小程序码
function getWechatQrcode($scene,$path){
    $url=$GLOBALS["wechat_baseurl"] . "wxa/getwxacodeunlimit";
    $body=[
        'scene'=>$scene,//示例：a=1&b=2
        'page'=>$path,//示例：'pages/menu/driver/info/index'
        'env_version'=>'release',//正式版为 "release"，体验版为 "trial"，开发版为 "develop"
        'width'=>1280,
        'check_path'=>false
    ];
    $file=http_wechat($url,$body);
    $date=date('Y-m-d');
    $name=mt_rand(1000,9999).time().mt_rand(100000,999999);
    $file=(new \utils\base64_to_file())->binary_get($name,$file);
    $res = oss::upload("qrcode/$date/" . $file["name"], $file["path"]);
    return $res["info"]["url"];
}

//扁平化数据转树状
function toTree(array $elements) {
    $tree = [];
    $items = [];

    // 构建一个以 ID 为键的哈希表
    foreach ($elements as $element) {
        $items[$element['id']] = $element;
        $items[$element['id']]['children'] = [];
    }

    // 遍历元素，将子节点挂载到父节点
    foreach ($items as $id => &$item) {
        if ($item['parent_id'] && isset($items[$item['parent_id']])) {
            $items[$item['parent_id']]['children'][] = &$item;
        } else {
            // 如果没有父节点，将其视为根节点
            $tree[] = &$item;
        }
    }

    return $tree;
}


//将B单位数据自动转为B、KB、MB、GB
function formatSize($size) {
    // 检查是否是数字字符串或数字
    if (!is_numeric($size)) {
        return $size;
    }

    // 将字符串转换为数字
    $size = floatval($size);

    // 定义单位数组
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];

    // 循环除以 1024，直到值小于 1024 或达到最大单位
    $i = 0;
    while ($size >= 1024 && $i < count($units) - 1) {
        $size /= 1024;
        $i++;
    }

    // 格式化输出，保留两位小数
    return sprintf('%.2f %s', $size, $units[$i]);
}

//根据xlxs文件路径，返回表格数据
function readXlsxFile($filePath)
{
    // 检查文件是否存在
    if (!file_exists($filePath)) {
        throw new Exception("文件不存在: $filePath");
    }

    // 创建解压目录
    $extractPath = sys_get_temp_dir() . '/xlsx_extract_' . uniqid();
    if (!mkdir($extractPath) && !is_dir($extractPath)) {
        throw new Exception("无法创建临时目录: $extractPath");
    }

    // 解压 .xlsx 文件
    $zip = new ZipArchive;
    if ($zip->open($filePath) === TRUE) {
        $zip->extractTo($extractPath);
        $zip->close();
    } else {
        throw new Exception("无法解压文件: $filePath");
    }

    // 读取 sharedStrings.xml 文件
    $sharedStrings = [];
    $sharedStringsPath = $extractPath . '/xl/sharedStrings.xml';
    if (file_exists($sharedStringsPath)) {
        $xml = simplexml_load_file($sharedStringsPath);
        foreach ($xml->si as $string) {
            $sharedStrings[] = (string)$string->t;
        }
    }

    // 读取 sheet1.xml 文件
    $data = [];
    $sheetPath = $extractPath . '/xl/worksheets/sheet1.xml';
    if (file_exists($sheetPath)) {
        $xml = simplexml_load_file($sheetPath);
        foreach ($xml->sheetData->row as $row) {
            $rowData = [];
            foreach ($row->c as $cell) {
                $cellValue = (string)$cell->v;
                $type = (string)$cell['t'];
                if ($type === 's') { // 如果是共享字符串
                    $rowData[] = $sharedStrings[$cellValue];
                } else {
                    $rowData[] = $cellValue;
                }
            }
            $data[] = $rowData;
        }
    }

    // 删除解压目录
    deleteDirectory($extractPath);

    return $data;
}

// 删除目录及其内容的辅助函数
function deleteDirectory($dir)
{
    if (!is_dir($dir)) {
        return;
    }
    $items = scandir($dir);
    foreach ($items as $item) {
        if ($item === '.' || $item === '..') {
            continue;
        }
        $path = $dir . DIRECTORY_SEPARATOR . $item;
        if (is_dir($path)) {
            deleteDirectory($path);
        } else {
            unlink($path);
        }
    }
    rmdir($dir);
}

